<?php
plugin('admin-top-user-management');
		$levels = $admin->getGroups();

	if($_GET['uid'] && $admin->canDo('Edit User')) {
		$id = sanitize_sql_string($_GET['uid']);
		if($_POST['updateUser']) {
			foreach($_POST as $key => $value) {
				$_POST[$key] = sanitize_sql_string($value);
			}
			if($_POST['password'] !== $_POST['confirm_password']) {
				$msgs[] = $admin->message('error', 'Passwords Don\'t Match', 'Please try again!');
				$error = 1;
			}
			if($_POST['email'] == "" || $_POST['username'] == "") {
				$msgs[] = $admin->message('error', 'Passwords Don\'t Leave The Email or Username Fields Blank', 'Fill them, then, please try again!');
				$error = 1;
			}
			if($error !== 1) {
				if($_POST['password'] == "" || $_POST['confirm_password'] == "") {
					$sql = "UPDATE ".DBTABLEPREFIX."users SET username = '{$_POST['username']}', level = '{$_POST['level']}', email = '{$_POST['email']}' WHERE id = '$id'";
					$query = $admin->db_query($sql) or die($admin->message('error', 'MySQL Error', $admin->db->error()));
					if($query) {
						$msgs[] = $admin->message('success', 'User Updated!', 'Please remember your password.');
					}
					else {
						$msgs[] = $admin->message('error', 'An Unknown Error Occured', 'An Unknown Error Occured');
					}
				}
				elseif ($_POST['password'] == $_POST['confirm_password']) {
					$hash = sha1($_POST['password']);
					$sql = "UPDATE ".DBTABLEPREFIX."users SET username = '{$_POST['username']}', level = '{$_POST['level']}', email = '{$_POST['email']}', password ='$hash' WHERE id = '$id'";
					$query = $admin->db_query($sql) or die($admin->message('error', 'MySQL Error', $admin->db->error()));
					if($query) {
						$msgs[] = $admin->message('success', 'User Updated!', 'Please remember your password.');
					}
					else {
						$msgs[] = $admin->message('error', 'An Unknown Error Occured', 'An Unknown Error Occured');
					}
				}
			}
			foreach ($msgs as $value) {
				$messages .= $value;
			}
		}
		$id = sanitize_sql_string($_GET['uid']);
		$sql = "SELECT * FROM ".DBTABLEPREFIX."users WHERE id = '{$id}'";
		$query = $admin->db_query($sql) or die($admin->db->error());
		$row = $admin->db->fetchAssoc($query);
		$level = $row['level'];
		$options = $admin->getGroupsOptions($level);
		$editForm = <<<HEREDOC
			<form action='?page=user-management&uid=$id' method='post'>
				<fieldset>
					<h2>Edit User {$row['username']}</h2>
					<div class='form-row'>
						<label for='username' class='username'>New Username:</label><span><input type='text' id='username' class='username' name='username' value='{$row['username']}' /></span>
					</div>		
					<div class='form-row'>
						<label for='password' class='password'>New Password:<span class="small gray">Leave this blank if you don't want to change the password</span></label><span><input type='password' class='password' name='password' /></span>
					</div>		
					<div class='form-row'>
						<label for='confirm_password' class='confirm_password'>New Password (confirm):<span class="small gray">Leave this blank if you don't want to change the password</span></label><span><input type='password' class='confirm_password' name='confirm_password' /></span>
					</div>		
					<div class='form-row'>
						<label for='email' class='email'>Email Address:</label><span><input type='text' class='email' name='email' value='{$row['email']}' /></span>
					</div>		
					<div class='form-row'>
						<label for='level' class='level'>Permissions Level:</label><span>
						<select name='level'>
							$options
						</select>
						</span>
					</div>		
					<div class='form-row form-row-last'>
						<label for='add_user' >Save:</label><span><input type='submit' value='Update User' name='updateUser' class='button' /></span>
					</div>
				</fieldset>
			</form>		
HEREDOC;
	} elseif(!$admin->canDo('Edit User')) {
			$output .= $admin->noAccess('Edit User', true);
		}
	if($_POST['name'] && $admin->canDo('Delete User')) {
		$name = sanitize_sql_string($_POST['name']);
		$sql = "DELETE FROM ".DBTABLEPREFIX."users WHERE username = '{$name}'";
		$query = $admin->db_query($sql) or die($admin->message('error', 'MySQL Error', $admin->db->error()));
		echo $admin->message('success', "User \"{$name}\" Deleted", "Let's hope that wasn't an accident...");
		exit();
	}elseif(!$admin->canDo('Delete User')) {
			echo $admin->noAccess('Edit User', true);
			exit();
		}
	else {
		if($_POST['add_user'] && $admin->canDo('Add User')) {
			$error = false;
			$sql = "SELECT * FROM ".DBTABLEPREFIX."users WHERE username = '".sanitize_sql_string($_POST['username'])."'";
			$query = $admin->db_query($sql) or die($admin->db->error());
			$num_rows = $admin->db->numRows($query);
			if($num_rows != 0) {
				$output .= $admin->message('error', 'That username already exists!', "Try to think of another one.");
				$error = true;
			}
			if($_POST['username'] == ""){
				$output .= $admin->message('error', 'Please put something in for the username.', "It isn't that hard, so just fix it now.");
				$error = true;
			}
			if($_POST['password'] != $_POST['confirm_password']) {
				$output .= $admin->message('error', 'Passwords don\'t match!', "Sorry but the passwords don't match. You typed {$_POST['password']} and {$_POST['confirm_password']} Try again!");
				$error = true;
			}
			if(validEmail($_POST['email']) == false) {
				$output .= $admin->message('error', "Hey! That isn't a real email!", "Sorry but you didn't put in a valid email. Please fix it.");
				$error = true;
			}
			if($error == false) {
				foreach($_POST as $key => $value) {
					$_POST[$key] = sanitize_sql_string($value);
				}
				$sql = "INSERT into ".DBTABLEPREFIX."users (username, password, level, email) VALUES ('".$_POST['username']."','".sha1($_POST['password'])."','".$_POST['level']."','".$_POST['email']."')";
				$query = $admin->db_query($sql) or die($admin->db->error());
				$output .= $admin->message('success', 'Woohoo! Your user "'.$_POST["username"].'" was added!', "He/She can now log in!");			
				if(!$query) {
					$output .= $admin->message('warning', 'An unknown error has occured', "An unknown error has occured");			
				}
			}
			if($error == true) {
				$output .= $admin->message('message', "Don't Forget!", "Set your permissions level again!");
			}
		foreach($levels as $key => $value) {
		
			$options .= "<option";
			$options .=">$value</option>";
		}
					$output .= "
				<form action='?page=user-management&add=user' method='post'>
					<fieldset>
						<h2>New User</h2>
						<div class='form-row'>
							<label for='username' class='username'>Username:</label><span><input type='text' class='username' id='username' name='username' value='{$_POST['username']}' /></span>
						</div>		
						<div class='form-row'>
							<label for='password' class='password'>Password:</label><span><input type='password' class='password' name='password' /></span>
						</div>		
						<div class='form-row'>
							<label for='confirm_password' class='confirm_password'>Password (confirm):</label><span><input type='password' class='confirm_password' name='confirm_password' /></span>
						</div>		
						<div class='form-row'>
							<label for='email' class='email'>Email Address:</label><span><input type='text' class='email' name='email' value='{$_POST['email']}' /></span>
						</div>		
						<div class='form-row'>
							<label for='level' class='level'>Permissions Level:</label><span>
							<select name='level'>
								$options
							</select>
							</span>
						</div>		
						<div class='form-row form-row-last'>
							<label for='add_user' >Save:</label><span><input type='submit' value='Add User' name='add_user' class='button' /></span>
						</div>
					<fieldset>
				</form>
				";
		} elseif(!$admin->canDo('Add User')) {
			$output .= $admin->noAccess('Add User', true);
		}
		elseif($admin->canDo('Add User')) {
		foreach($levels as $key => $value) {
		
			$options .= "<option";
			$options .=">$value</option>";
		}
		$output .= "
			<form action='?page=user-management&add=user' method='post'>
				<fieldset>
					<h2>New User</h2>
					<div class='form-row'>
						<label for='username' class='username'>Username:</label><span><input type='text' id='username' class='username' name='username' /></span>
					</div>		
					<div class='form-row'>
						<label for='password' class='password'>Password:</label><span><input type='password' class='password' name='password' /></span>
					</div>		
					<div class='form-row'>
						<label for='confirm_password' class='confirm_password'>Password (confirm):</label><span><input type='password' class='confirm_password' name='confirm_password' /></span>
					</div>		
					<div class='form-row'>
						<label for='email' class='email'>Email Address:</label><span><input type='text' class='email' name='email' /></span>
					</div>		
					<div class='form-row'>
						<label for='level' class='level'>Permissions Level:</label><span>
						<select name='level'>
								$options
						</select>
						</span>
					</div>		
					<div class='form-row form-row-last'>
						<label for='add_user' >Save:</label><span><input type='submit' value='Add User' name='add_user' class='button' /></span>
					</div>
				</fieldset>
			</form>
			";
		}
		else {
			$output .= $admin->noAccess('Add User', true);
		}	
	$table .= "\n
	<div class='right disable-warnings'>Disable warnings when deleting users? <input type='checkbox' id='disable-warnings-checkbox' class='checkbox'/></div>
	<table cellspacing='0' border='0' id='users' cellpadding='0'>\n\t<thead>\n\t\t<tr>\n\t\t\t<th>Username</th><th>Email</th><th>Level</th><th>Actions</th>\n\t\t</tr>\n\t<tbody>";
	$sql = "SELECT * FROM ".DBTABLEPREFIX."users";
	$query = $admin->db_query($sql) or die($admin->db->error());
	while($row = $admin->db->fetchArray($query)) {
		$table .= "\n\t\t<tr><td class='username'>{$row['username']}</td>
		<td>{$row['email']}</td><td>{$row['level']}</td>
		<td style='text-align:center;'><a href='javascript:;' class='delete-user helplink' title='Delete this user'>
			<img src='".THEME_URL."includes/admin/images/icons/delete-16x16.png' alt='Delete' /></a>
			<a href='admin.php?page=user-management&uid={$row['id']}' title='Edit this user' class='helplink'>
				<img src='".THEME_URL."includes/admin/images/icons/edit-16x16.png' alt='Edit' />
				</a></td></tr>";
	}
	$table .= "</tbody></table>";

}

$admin->page_info['content']['page_title'] = "User Management";
$admin->page_info['content']['page_content']	= $messages.$editForm.$table.$output;
plugin('admin-bottom-user-management');
//Display page
include(BASE_URL.'includes/admin/admin.php');

?>